package com.small.common.filter;


import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.small.common.base.BaseConstants;
import com.small.common.exception.auth.JwtTokenExpiredException;
import com.small.common.msg.Msg;
import com.small.common.msg.MsgCommon;
import com.small.common.util.jwt.JwtHelper;
import com.small.common.util.jwt.config.UserAuthConfig;
import com.small.common.util.jwt.info.IJwtInfo;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Resource
    private UserAuthConfig userAuthConfig;

    public static final String USER_KEY = "userId";
    
    private static final String NOT_LOGIN = JSON.toJSONString(MsgCommon.TIP_10000);

    private static final String EXPIRED_LOGIN = JSON.toJSONString(MsgCommon.TIP_10002);
    
    private static final String NO_TOKEN = JSON.toJSONString(MsgCommon.TIP_10016);
    
    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        try {
            //获取head中的token
            String authToken = request.getHeader(userAuthConfig.getTokenHeader());
            log.info("获取head中的token:"+authToken);
            //如果head中没有token获取参数中的
            if (StringUtils.isBlank(authToken)) {
                authToken = request.getParameter(userAuthConfig.getTokenHeader());
            }
            if (StringUtils.isBlank(authToken)) {
                this.writeResponse(response, NO_TOKEN);
                return false;
            } else {
                //校验token
                IJwtInfo iJwtInfo = JwtHelper.getTokenInfo(authToken, userAuthConfig.getPubKeyPath());
            }
            return true;
        } catch (Exception e) {
            if (e instanceof JwtTokenExpiredException) {
                return false;
            } else {
//                FilterUtil.setFailedRequest(FilterUtil.NOT_LOGIN);
                return false;
            }
        }
    }
    
    private void writeResponse(HttpServletResponse response, String resultEnum) {
        PrintWriter pw = null;
        try {
            response.setHeader("Content-Type", "application/json");
            response.setCharacterEncoding("UTF-8");
            pw = response.getWriter();
            pw.write(resultEnum);
            pw.close();
        } catch (Exception e) {
//            log.error("response.getWriter异常", e);
        } finally {
            if (pw != null) {
                pw.close();
            }
        }
    }
}